package com.example.myredisinaction;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class AutoCompleteController {

    @Autowired
    RedisTemplate<String, Serializable> redisTemplate;
    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    static AtomicInteger atomicInteger = new AtomicInteger(0);

    @GetMapping("getNames")
    public List<Object> getNames(String input) {
        char last = input.charAt(input.length() - 1);
        char replace = (char) (last - 1);
        String prefix = input.substring(0, input.length() - 1) + replace + "{";
        String surfix = input + "{";
        log.info(prefix + "," + surfix);

        String uuid = UUID.fastUUID().toString();
        prefix += uuid;
        surfix += uuid;
        String zSetKey = "names";
        /*RedisConnection connection = redisConnectionFactory.getConnection();
        System.out.println(connection);
        connection.openPipeline();*/
        ZSetOperations<String, Serializable> zSetOp = redisTemplate.opsForZSet();
        zSetOp.add(zSetKey, prefix, 0);
        zSetOp.add(zSetKey, surfix, 0);
        List<Object> result = new ArrayList<>();
        while (true) {
            try {
                redisTemplate.watch(zSetKey);
                Long preIndex = zSetOp.rank(zSetKey, prefix);
                Long surIndex = zSetOp.rank(zSetKey, surfix);
                if (preIndex == null || surIndex == null) {
                    break;
                }
                long realSurIndex = Math.min(preIndex + 9, surIndex - 2);
                redisTemplate.multi();

                zSetOp.remove(zSetKey, prefix, surfix);
                System.out.println(atomicInteger.incrementAndGet() + ", " + prefix + ", " + surfix);
                zSetOp.range(zSetKey, preIndex, realSurIndex);

                result = redisTemplate.exec();
                break;
            } catch (Exception e) {
                log.info("事务失败，重试", e);
            }
        }
        return result.stream().filter(item -> !String.valueOf(item).contains("{")).collect(Collectors.toList());
    }
}
